<template>
  <div>
    <div class="transfer">
      <div class="leftTransfer">
        <div class="leftTransfer_title">
          <el-checkbox
            :indeterminate="left.isIndeterminate"
            v-model="left.checkAll"
            @change="leftHandleCheckAllChange"
            >{{ titles[0] }}</el-checkbox
          >
          <span
            >{{ left.transferDataChecked.length }}/{{
              left.childrenNum || 0
            }}</span
          >
        </div>
        <el-input
          @input="transferInputLeft"
          class="transfer_input"
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="left.inputValue"
        />
        <div style="margin: 5px 0"></div>
        <el-scrollbar class="transfer_group">
          <el-tree
            ref="leftTree"
            :data="left.transferData"
            show-checkbox
            node-key="key"
            :default-checked-keys="left.checkedKeys"
            default-expand-all
            :expand-on-click-node="false"
            :props="defaultProps"
            @check="leftHandleChecked"
          />
        </el-scrollbar>

        <el-pagination
          small
          class="pagination"
          :pager-count="5"
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="transferButton">
        <el-button
          type="primary"
          :disabled="!left.transferDataChecked.length"
          @click="push"
          icon="el-icon-arrow-right"
        ></el-button>
        <el-button
          type="primary"
          :disabled="!right.transferDataChecked.length"
          @click="del"
          icon="el-icon-arrow-left"
        ></el-button>
      </div>
      <div class="rightTransfer">
        <div class="rightTransfer_title">
          <el-checkbox
            :indeterminate="right.isIndeterminate"
            v-model="right.checkAll"
            @change="rightHandleCheckAllChange"
            >{{ titles[1] }}</el-checkbox
          >
          <!-- <span>{{ titles[1] }}</span> -->
          <span
            >{{ right.transferDataChecked.length }}/{{
              right.transferData.length
            }}</span
          >
        </div>
        <el-input
          @input="transferInputRight"
          class="transfer_input"
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="right.inputValue"
        />
        <div style="margin: 5px 0"></div>
        <el-scrollbar class="transfer_group">
          <el-tree
            ref="rightTree"
            :data="right.transferData"
            show-checkbox
            node-key="key"
            default-expand-all
            :default-checked-keys="right.checkedKeys"
            :expand-on-click-node="false"
            :props="defaultPropsRight"
            @check="rightHandleChecked"
          />
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
  <script>
export default {
  props: {
    titles: {
      type: Array,
      default: () => ["待选列表", "已选列表"],
    },
    listApi: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      left: {
        inputValue: "",
        isIndeterminate: false, //半选按钮
        checkAll: false, //是否点击全选
        transferData: [
          {
            key: 1,
            parent_id: "1",
            name: "选项1",
            children: [
              {
                key: 11,
                parent_id: "2",
                name: "选项1-1",
              },
              {
                key: 12,
                parent_id: "3",
                name: "选项1-2",
              },
            ],
          },
          {
            key: 2,
            parent_id: "4",
            name: "选项2",
            children: [
              {
                key: 21,
                parent_id: "5",
                name: "选项2-1",
              },
              {
                key: 22,
                parent_id: "6",
                name: "选项2-2",
              },
            ],
          },
        ],
        checkedKeys: [],
        transferDataAll: [], //穿梭框左侧全部数据记录
        transferDataChecked: [], //穿梭框左侧选中数据
        originData: [], //原始数据
      },
      right: {
        inputValue: "",
        isIndeterminate: false, //半选按钮
        checkAll: false, //是否点击全选
        checkedKeys: [],
        transferData: [
          {
            key: 3,
            name: "选项3",
            parent_id: "7",
            children: [
              {
                key: 31,
                parent_id: "8",
                name: "选项3-1",
              },
              {
                key: 32,
                parent_id: "9",
                name: "选项3-2",
              },
            ],
          },
          {
            key: 4,
            name: "选项4",
            parent_id: "10",
            children: [
              {
                key: 41,
                parent_id: "11",
                name: "选项4-1",
              },
              {
                key: 42,
                parent_id: "12",
                name: "选项4-2",
              },
            ],
          },
        ],
        transferDataAll: [], //穿梭框左侧全部数据记录
        transferDataChecked: [], //穿梭框右侧选中数据
      },
      total: 0,
      queryParams: {
        page: 1,
        per_page: 10,
      },
      defaultProps: {
        label: "name",
        id: "key",
        children: "children",
      },
      defaultPropsRight: {
        label: "name",
        id: "key",
        children: "children",
      },
    };
  },
  methods: {
    // 左侧全选按钮勾选
    leftHandleCheckAllChange(value) {
      this.left.checkedKeys = value
        ? this.getAllNodeIds(this.left.transferData)
        : [];
      this.left.transferDataChecked = (this.left.transferData || []).filter(
        (item) => item.key !== 0
      );
      this.$nextTick(() => {
        this.$refs.leftTree.setCheckedKeys(this.left.checkedKeys);
      });
    },
    // 右侧全选按钮勾选
    rightHandleCheckAllChange(value) {
      this.right.checkedKeys = value
        ? this.getAllNodeIdsRight(this.right.transferData)
        : [];
        this.right.transferDataChecked = this.right.transferData || [];
      this.$nextTick(() => {
        this.$refs.rightTree.setCheckedKeys(this.right.checkedKeys);
      });
    },
    // 左侧的
    getAllNodeIds(nodes) {
      return nodes.reduce((keys, node) => {
        keys.push(node.key);
        if (node.children) {
          keys.push(...this.getAllNodeIds(node.children));
        }
        return keys;
      }, []);
    },

    // 右侧的
    getAllNodeIdsRight(nodes) {
      return nodes.reduce((keys, node) => {
        keys.push(node.key);
        if (node.children) {
          keys.push(...this.getAllNodeIds(node.children));
        }
        return keys;
      }, []);
    },

    // 初始化数据
    initTransferData() {
      props.listApi({ params: this.queryParams }).then((response) => {
        console.log(response, "response");
        let childrenNum = 0;
        this.left.transferData = (response.data.list || []).map((item) => {
          if (item.children) {
            item.children.forEach((item2) => {
              item2.type_name_second = item.type_name + "-" + item2.type_name;
            });
            childrenNum += item.children.length;
          }
          if (item.children.length === 0) {
            item.disabled = true;
          }
          return item;
        });
        this.left.childrenNum = childrenNum;
        this.left.originData = JSON.parse(
          JSON.stringify(this.left.transferData)
        );
        this.left.transferData.map((item, index) => {
          item.page = this.queryParams.page;
        });
        this.total = response.data.total;
        this.left.transferDataAll = this.left.transferData;

        // 删除左侧的数据
        this.delLeftData();
      });
    },

    // 删除左侧数据
    delLeftData() {
      // 获得一个右边的数据，只有纯id
      let checkedIdArr = this.right.transferData.map((item) => {
        return item[this.defaultProps.id];
      });
      // 左侧数据删除
      this.left.transferData = this.left.transferData.filter((item) => {
        console.log(item,"item");
        // 删除时，判断左侧的一级数据的二级是否全部转移，如果是，则一级也删除，否则，只删除二级
        if (item.children && item.children.length > 0) {
          let childrenArr = item.children.map((item2) => {
            return item2[this.defaultProps.id];
          });
          if (childrenArr.every((item3) => checkedIdArr.includes(item3))) {
            return false;
          } else {
            item.children = item.children.filter((item2) => {
              if (!checkedIdArr.includes(item2[this.defaultProps.id])) {
                return item2;
              }
            });
            return item;
          }
        } else {
          if (!checkedIdArr.includes(item[this.defaultProps.id])) {
            return item;
          }
        }
      });
    },

    // 左侧勾选数据
    leftHandleChecked(data, nodes) {
      this.left.transferDataChecked = (nodes.checkedNodes || []).filter(
        (item) => item.pid !== 0
      );
      const checkedKeys = nodes.checkedNodes.map((node) => node.key);
      this.left.isIndeterminate =
        checkedKeys.length > 0 &&
        checkedKeys.length < this.getAllNodeIds(this.left.transferData).length;
      this.left.checkAll =
        checkedKeys.length ===
        this.getAllNodeIds(this.left.transferData).length;
      this.left.checkedKeys = checkedKeys;
    },

    // 右侧勾选数据
    rightHandleChecked(data, nodes) {
      this.right.transferDataChecked = nodes.checkedNodes || [];
      const checkedKeys = nodes.checkedNodes.map((node) => node.key);
      this.right.isIndeterminate =
        checkedKeys.length > 0 &&
        checkedKeys.length <
          this.getAllNodeIdsRight(this.right.transferData).length;
      this.right.checkAll =
        checkedKeys.length ===
        this.getAllNodeIdsRight(this.right.transferData).length;
      this.right.checkedKeys = checkedKeys;
    },

    // 穿梭框选中数据
    push() {
      // 数据移到右侧
      this.right.transferData = [
        ...this.right.transferData,
        this.left.transferDataChecked[0],
      ].sort((a, b) => {
        return a[this.defaultProps.id] - b[this.defaultProps.id];
      });
      console.log(this.left.transferDataChecked,"aer")
      this.right.transferDataAll = this.right.transferData;
       debugger
      // 删除左侧的数据
      this.delLeftData();

      this.left.transferDataAll = this.left.transferData;
      // 每次推送完之后，重置选中框
      this.left.transferDataChecked = [];
      this.left.isIndeterminate = false;
      this.left.checkAll = false;
    },
    // 穿梭框删除数据 回显的时候根据current回显到当前
    del() {
      //过滤当前页选中的数据
      let arr = this.right.transferDataChecked || [];
      this.left.originData.forEach((item) => {
        let node = arr.filter((item2) => item2.pid === item.id);

        if (node.length) {
          let ev = this.left.transferData.find((item2) => {
            return node[0].pid === item2.id;
          });
          console.log(ev, "ev11");
          if (ev) {
            ev.children = [...ev.children, ...node];
          } else {
            let ev2 = this.left.originData.find((item2) => {
              return node[0].pid === item2.id;
            });
            if (ev2)
              this.left.transferData.push({
                ...ev2,
                children: [...node],
              });
          }
        }
      });
      console.log(arr, "arr");
      // 数据移到左侧
      // this.left.transferData = [...this.left.transferData, ...arr].sort((a, b) => {
      //   return a[this.defaultProps.id] - b[this.defaultProps.id]
      // })
      this.left.transferDataAll = this.left.transferData;
      // 获得一个右边的数据，只有纯id
      let checkedIdArr = this.right.transferDataChecked.map((item) => {
        return item[this.defaultProps.id];
      });
      // 删除选中的数据
      this.right.transferData = this.right.transferData.filter((item) => {
        if (!checkedIdArr.includes(item[this.defaultProps.id])) {
          return item;
        }
      });
      this.right.transferDataAll = this.right.transferData;
      // 每次推送完之后，重置选中框
      this.right.transferDataChecked = [];
      this.right.isIndeterminate = false;
      this.right.checkAll = false;
    },

    handleCurrentChange(val) {
      this.queryParams.page = val;
      initTransferData();
    },

    transferInputLeft() {
      if (this.left.inputValue) {
        this.left.transferData = this.left.transferData.filter(
          (p) => p[this.defaultProps.label].indexOf(this.left.inputValue) !== -1
        );
      } else {
        this.left.transferData = this.left.transferDataAll;
      }
    },
    transferInputRight() {
      if (this.right.inputValue) {
        this.right.transferData = this.right.transferData.filter(
          (p) =>
            p[this.defaultProps.label].indexOf(this.right.inputValue) !== -1
        );
      } else {
        this.right.transferData = this.right.transferDataAll;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.transfer {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .transferButton {
    .el-button {
      display: block;
      margin: 10px 0;
    }
  }
  .el-checkbox {
    line-height: 30px;
  }
  .transfer_input {
    margin: 10px 15px 0 15px;
    width: 85%;
    .el-input--medium .el-input__inner {
      height: 36px;
      line-height: 36px;
      border-radius: 16px;
    }
  }
  .leftTransfer,
  .rightTransfer {
    height: 425px;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    overflow: hidden;
    background: #ffffff;
    display: inline-block;
    vertical-align: middle;
    width: 250px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    margin: 0 10px;

    .el-checkbox {
      display: block;
    }
    .pagination {
      position: absolute;
      bottom: -4px;
      right: 0;
    }
    .leftTransfer_title,
    .rightTransfer_title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      line-height: 40px;
      background: #f5f7fa;
      margin: 0;
      padding-left: 15px;
      border-bottom: 1px solid #e6ebf5;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      color: #000000;
      padding-right: 15px;
      align-items: center;
    }
  }
}
.transfer_group {
  padding-left: 15px;
  height: calc(100% - 105px);
}
</style>

